package edu.ajou.scw;

import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

import java.net.*;
import java.io.*;

import org.json.simple.JSONObject;

public class PushSender {       	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PushSender() {
        
    }
    
    public void sendPush(String id, String type, String content)
    {
    	DatabaseConnector conn = new DatabaseConnector();
    	
    	String[] login_info = conn.getLoginInfo(id);
    	
    	conn.close();
    	
    	if (login_info != null)
    	{
    		if (login_info[2].equals("0"))
    		{
    			Log.d(id + " isn't logged in now.");
    		}
    		
    		if (login_info[0].equals("android"))
    		{
    			Log.d("Sending Push Notification to " + id + "(android)");
    			//sendGCM(login_info[1], type, content);
    			Thread gcmThread = new Thread(new GCMThread(login_info[1], type, content));
    			gcmThread.start();
    		}
    		else if (login_info[0].equals("pc"))
    		{
    			//String[] addr = login_info[1].split(":");
    			Log.d("Sending Push Notification to " + id + "(pc)");
    			//sendSocket(id, type, content);
    			Thread socketThread = new Thread(new SocketPushThread(id, type, content));
    			socketThread.start();
    		}
    	}
    }
    
    public void sendSocket(String id, String type, String content)
    {
    	try
    	{
    		Log.d("Push message sent through socket connection to " + id);
    		//System.out.println("# Socket Push Notification Sent to " + ipAddr + ":" + port);
    		Socket socket = new Socket("127.0.0.1", 8787);
    		OutputStream os = socket.getOutputStream();
    		PrintWriter pw = new PrintWriter(os);
    		
    		JSONObject obj = new JSONObject();
    		obj.put("id", id);
    		obj.put("content", content);
    		
    		String message = obj.toJSONString();
    		pw.write(message);
    		pw.flush();
    		
    		pw.close();
    		socket.close();
    	}
    	catch (Exception e)
    	{
    	
    	}
    }
    
    public static final String API_KEY = "AIzaSyBMMV0uR6S8n333JsJ7LLU2Hdtq8O8eQZ0";
    public void sendGCM(String regId, String type, String message)
    {
	    Sender sender;
	    Message msg;
	    
	    sender = new Sender(API_KEY);
		Message.Builder builder = new Message.Builder();

		builder.addData("type", type);
		builder.addData("content", message);
		
		msg = builder.build();		
		
		try {
			if (regId.equals(""))
				return;
			Result result = sender.send(msg, regId, 5);
			Log.d("GCM Push Message Sent to " + regId);
			String error = result.getErrorCodeName();
			String msgId = result.getMessageId();
			
			if (msgId != null)
			{
				String canonicalId = result.getCanonicalRegistrationId();
				if (canonicalId != null)
				{
					System.out.println("# same device has more than on registration ID: update database");
				}
			}
			
			if (error != null)
			{
				if (error.equals(Constants.ERROR_NOT_REGISTERED))
				{
					System.out.println("# application has been removed from device - unregister database");
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
    }
}
